package com.ruoyi.project.system.user.controller;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.*;
import com.ruoyi.common.utils.security.ShiroUtils;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.channel.businessInfo.domain.BusinessInfo;
import com.ruoyi.project.channel.businessInfo.service.IBusinessInfoService;
import com.ruoyi.project.channel.clickFormUser.domain.ClickFormUser;
import com.ruoyi.project.channel.clickFormUser.service.IClickFormUserService;
import com.ruoyi.project.channel.smsInfo.service.ISmsInfoService;
import com.ruoyi.project.pay.PayConfig;
import com.ruoyi.project.pay.mail.IMailService;
import com.ruoyi.project.system.config.service.IConfigService;
import com.ruoyi.project.system.user.domain.User;
import com.ruoyi.project.system.user.domain.UserRole;
import com.ruoyi.project.system.user.service.IUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.aspectj.weaver.loadtime.Aj;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 登录验证
 *
 * @author ruoyi
 */
@Controller
@RequestMapping("/*")
public class RegisterController extends BaseController {
    @Autowired
    private IUserService userService;
    @Autowired
    private PayConfig payConfig;
    @Autowired
    private IClickFormUserService clickFormUserService;
    @Autowired
    private IBusinessInfoService businessInfoService;
    @Autowired
    private IConfigService configService;
    @Autowired
    private ISmsInfoService smsInfoService;

    @PostMapping("/register")
    @ResponseBody
    public AjaxResult register(@RequestBody HashMap<String, String> info, HttpServletRequest request) {
        // 校验SMS验证码 TODO：
        // 验证 phone是否注册过
        User searchUser = new User();
        searchUser.setUserName(info.get("userName"));
        List<User> users = userService.selectUserList(searchUser);
        if (users.size() > 0) {
            return AjaxResult.error("user name has exists");
        }
//        boolean flag = smsInfoService.validateCode(info.get("phoneNumber"), info.get("sms"));
//        if(flag == false){
//            return AjaxResult.error("sms error");
//        }
        BusinessInfo clickFormUser = new BusinessInfo();
        clickFormUser.setInvitationCode(info.get("invitationCode"));
        clickFormUser.setStatus("0");
        clickFormUser.setPayPwd(info.get("payPassword"));
//        clickFormUser.setContactNo(info.get("userName"));
        clickFormUser.setLevelId(payConfig.getVip()); // 普通用户
        // 获取invitationCode
        String invitationCode = clickFormUser.getInvitationCode();
        if (invitationCode == null) {
            return AjaxResult.error("invitationCode must not null");
        }
//        long longCode = 0L;
//        try {
//            longCode = Long.valueOf(invitationCode);
//        } catch (Exception e) {
//            return AjaxResult.error("invitationCode must be number");
//        }
        // 看下这个ip是否注册过
        String ip = IpUtils.getIpAddr(request);
        BusinessInfo search = new BusinessInfo();
        search.setIp(ip);
        List<BusinessInfo> infos = businessInfoService.selectBusinessInfoList(search);
        if (!infos.isEmpty()) {
            return AjaxResult.error("exists ip");
        }
        clickFormUser.setIp(ip);
        search = new BusinessInfo();
        search.setInvitationCode(invitationCode.toUpperCase());
        infos = businessInfoService.selectBusinessInfoList(search);
        if (infos.isEmpty()) {
            // 查找业务员
            User searchU = new User();
            searchU.setRemark(invitationCode);
            List<User> parentUsers = userService.selectUserList(searchU);
            if (parentUsers.isEmpty()) {
                // 业务员如果也是空的则报错
                return AjaxResult.error("invitationCode not fount");
            }
            clickFormUser.setRootUserId(parentUsers.get(0).getUserId());
        } else {
            // 上级用户
            BusinessInfo businessInfo = infos.get(0);
            // 一级代理
            clickFormUser.setParentUserId(infos.get(0).getUserId());
            if (businessInfo.getParentUserId() != null) {
                //上级的一级代理就是 二级代理
                clickFormUser.setSecondParentUserId(businessInfo.getParentUserId());
                // 三级代理
                if (businessInfo.getSecondParentUserId() != null) {
                    clickFormUser.setThirdParentUserId(businessInfo.getSecondParentUserId());
                }
            }
            if (businessInfo.getRootUserId() != null) {
                clickFormUser.setRootUserId(businessInfo.getRootUserId());
            }
        }

//        else {
//            clickFormUser.setRootUserId(infos.get(0).getUserId());
//        }

        User user = new User();
        user.setDeptId(payConfig.getDept()); // 刷单部门
        String userName = info.get("userName");
        User tmpUser = userService.selectUserByLoginName(userName);
        if (tmpUser != null) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", "1"); // 用户已存在
            return AjaxResult.error("user name has already exist", jsonObject);
        }
        user.setUserName(userName);
        user.setLoginName(userName);
        user.setPassword(info.get("password"));
        user.setStatus("0");
        user.setRoleId(payConfig.getRole()); // 刷单角色
        Long[] l = {payConfig.getRole()};
        user.setRoleIds(l);
        user.setPhonenumber(info.get("phoneNumber"));
        // 如果是代理商, 添加的商户默认加上归属代理商信息
        userService.insertClickFormUser(user);
        return toAjax(businessInfoService.insertBusinessInfo(clickFormUser, user));
    }

    @RequiresPermissions("system:user:addBusiness")
    @PostMapping("/registerByAdmin")
    @ResponseBody
    public AjaxResult registerByAdmin(BusinessInfo clickFormUser, User user) {
        // 校验SMS验证码 TODO：
        clickFormUser.setStatus("0");
        clickFormUser.setPayPwd(user.getPassword());
        clickFormUser.setContactNo(user.getPhonenumber());
        clickFormUser.setLevelId(payConfig.getVip()); // 普通用户
        // 获取invitationCode
        User parentUser = ShiroUtils.getSysUser();
        // 非默认邀请码 使用用户邀请码
        if (clickFormUser.getInvitationCode() == null || clickFormUser.getInvitationCode().isEmpty()) {
            // remark 存放的是邀请码
            clickFormUser.setInvitationCode(parentUser.getRemark());
            clickFormUser.setRootUserId(parentUser.getUserId());
        } else {
            BusinessInfo searchIn = new BusinessInfo();
            searchIn.setInvitationCode(clickFormUser.getInvitationCode());
            List<BusinessInfo> businessInfos = businessInfoService.selectBusinessInfoList(searchIn);
//            BusinessInfo businessInfo = businessInfoService.selectBusinessInfoById(parentUser.getUserId());
            if (!businessInfos.isEmpty()) {
                BusinessInfo businessInfo = businessInfos.get(0);
                        // 一级代理
                clickFormUser.setParentUserId(businessInfo.getUserId());
                if (businessInfo.getParentUserId() != null) {
                    //上级的一级代理就是 二级代理
                    clickFormUser.setSecondParentUserId(businessInfo.getParentUserId());
                    // 三级代理
                    if (businessInfo.getSecondParentUserId() != null) {
                        clickFormUser.setThirdParentUserId(businessInfo.getSecondParentUserId());
                    }
                }
                if (businessInfo.getRootUserId() != null) {
                    clickFormUser.setRootUserId(businessInfo.getRootUserId());
                }
            }
        }

        user.setDeptId(payConfig.getDept()); // 刷单部门
        String userName = user.getUserName();
        User tmpUser = userService.selectUserByLoginName(userName);
        if (tmpUser != null) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", "1"); // 用户已存在
            return AjaxResult.error("user name has already exist", jsonObject);
        }
        user.setUserName(userName);
        user.setLoginName(userName);
        user.setPassword(user.getPassword());
        user.setStatus("0");
        user.setRoleId(payConfig.getRole()); // 刷单角色
        Long[] l = {payConfig.getRole()};
        user.setRoleIds(l);
        // 如果是代理商, 添加的商户默认加上归属代理商信息
        userService.insertClickFormUser(user);
        clickFormUser.setOrderPrice(new BigDecimal("100")); // 假人标志
        return toAjax(businessInfoService.insertBusinessInfo(clickFormUser, user));
    }

    @GetMapping("/getPhoneCode")
    @ResponseBody
    public AjaxResult getCode(String phoneNumber) {
        if (null == phoneNumber || phoneNumber.trim().equals("")) {
            return AjaxResult.error("error");
        }

        User user = new User();
        user.setPhonenumber(phoneNumber.trim());
        List<User> users = userService.selectUserList(user);
        if (users.size() > 0) {
            return AjaxResult.error("phone already exists");
        }
        return smsInfoService.doSendCode(user);
    }

    @PostMapping("/bindingPhone")
    @ResponseBody
    public AjaxResult bindingPhone(@RequestBody HashMap<String, String> info) {
        User searchUser = new User();
        searchUser.setPhonenumber(info.get("phoneNumber"));
        List<User> users = userService.selectUserList(searchUser);
        if (users.size() > 0) {
            return AjaxResult.error("phoneNumber exists");
        }
        boolean flag = smsInfoService.validateCode(info.get("phoneNumber"), info.get("sms"));
        if (flag == false) {
            return AjaxResult.error("sms error");
        }
        User user = ShiroUtils.getSysUser();
        user.setPhonenumber(info.get("phoneNumber"));
        userService.updateUserInfo(user);
        return AjaxResult.success("success");
    }
}
